﻿using System.Web.Mvc;

using Devbridge.IPolice.DomainModel;
using Devbridge.IPolice.ServiceContracts;
using Devbridge.IPolice.Services;
using Devbridge.IPolice.Web.Models.PoliceOfficer;

namespace Devbridge.IPolice.Web.Controllers
{
    public class PoliceOfficerController : Controller
    {
        private IPoliceOfficerService policeOfficerService;

        public PoliceOfficerController()
        {
            policeOfficerService = new PoliceOfficerService();
        }

        public ActionResult List(string filterByName)
        {
            var data = policeOfficerService.GetPoliceOfficers();

            OfficerListViewModel model = new OfficerListViewModel();
            foreach (var officer in data)
            {
                model.Officers.Add(new OfficerViewModel
                                       {
                                           Id = officer.Id,
                                           FullName = string.Format("{0} {1}", officer.FirstName, officer.LastName) .Trim(),
                                           PhoneNumber = officer.PhoneNumber
                                       });
            }            

            return View(model);
        }

        public ActionResult Delete(int id)
        {
            policeOfficerService.RemovePoliceOfficerById(id);

            return RedirectToAction("List");
        }

        [HttpGet]
        public ActionResult Add()
        {
            return View(new AddOfficerViewModel());
        }

        [HttpPost]
        public ActionResult Add(AddOfficerViewModel model)
        {
            if (ModelState.IsValid)
            {
                policeOfficerService.AddPoliceOfficer(new PoliceOfficer
                                                          {
                                                              FirstName = model.FirstName,
                                                              LastName = model.LastName,
                                                              PhoneNumber = model.PhoneNumber
                                                          });
                return RedirectToAction("List");
            }
            
            return View(model);
        }

        protected override void Dispose(bool disposing)
        {
            policeOfficerService.Dispose();
            base.Dispose(disposing);
        }
    }
}
